package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author 岩冰
 * @version 1.0
 * @date:2018/9/26
 */
@Service
public class UploadService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadService.class);
    private static  final List<String> suffixes = Arrays.asList("image/png", "image/jpeg");
    @Autowired
    private FastFileStorageClient fileStorageClient;
    public String upload(MultipartFile file) {
        //判断文件是否符合规则
        //1 文件类型
        try {
            if (!suffixes.contains( file.getContentType())) {
                return null;
            }
            //2判断文件内容是不是图片
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage==null ) {
                //如果图片信息为空的话
                return null;
            }
            //将文件存储到指定的位置
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            StorePath storePath = fileStorageClient.uploadFile(file.getInputStream(), file.getSize(),
                    extension, null);
            return "http://image.leyou.com/"+storePath.getFullPath();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
